const axios = require('axios');
require('dotenv').config();

class Tripo3DClient {
  constructor() {
    this.apiKey = process.env.TRIPO3D_API_KEY;
    this.clientId = process.env.TRIPO3D_CLIENT_ID;
    this.baseUrl = process.env.TRIPO3D_API_BASE_URL || 'https://api.tripo3d.ai/v1';
    
    this.client = axios.create({
      baseURL: this.baseUrl,
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'X-Client-Id': this.clientId,
        'Content-Type': 'application/json'
      }
    });
  }

  /**
   * 从2D图片生成3D模型
   * @param {string} imageUrl - 图片URL
   * @param {Object} options - 额外选项
   * @returns {Promise<Object>} API响应
   */
  async generate3DFromImage(imageUrl, options = {}) {
    try {
      const response = await this.client.post('/generate', {
        image_url: imageUrl,
        ...options
      });
      return response.data;
    } catch (error) {
      console.error('Error generating 3D model from image:', error.response?.data || error.message);
      throw error;
    }
  }

  /**
   * 上传图片并生成3D模型
   * @param {Buffer} imageBuffer - 图片缓冲区
   * @param {string} imageType - 图片类型
   * @param {Object} options - 额外选项
   * @returns {Promise<Object>} API响应
   */
  async generate3DFromUploadedImage(imageBuffer, imageType, options = {}) {
    try {
      // 首先上传图片获取URL
      const formData = new FormData();
      formData.append('image', new Blob([imageBuffer], { type: imageType }));
      
      // 创建用于文件上传的客户端实例，因为Content-Type需要是multipart/form-data
      const uploadClient = axios.create({
        baseURL: this.baseUrl,
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
          'X-Client-Id': this.clientId
        }
      });
      
      const uploadResponse = await uploadClient.post('/upload', formData);
      const imageUrl = uploadResponse.data.image_url;
      
      // 使用获取的图片URL生成3D模型
      return await this.generate3DFromImage(imageUrl, options);
    } catch (error) {
      console.error('Error generating 3D model from uploaded image:', error.response?.data || error.message);
      throw error;
    }
  }

  /**
   * 获取生成任务的状态
   * @param {string} taskId - 任务ID
   * @returns {Promise<Object>} 任务状态
   */
  async getTaskStatus(taskId) {
    try {
      const response = await this.client.get(`/tasks/${taskId}`);
      return response.data;
    } catch (error) {
      console.error('Error getting task status:', error.response?.data || error.message);
      throw error;
    }
  }

  /**
   * 下载生成的3D模型
   * @param {string} modelId - 模型ID
   * @param {string} format - 模型格式 (glb, obj, stl等)
   * @returns {Promise<Buffer>} 模型文件数据
   */
  async downloadModel(modelId, format = 'glb') {
    try {
      const response = await this.client.get(`/models/${modelId}/download`, {
        params: { format },
        responseType: 'arraybuffer'
      });
      return Buffer.from(response.data);
    } catch (error) {
      console.error('Error downloading 3D model:', error.response?.data || error.message);
      throw error;
    }
  }
}

module.exports = Tripo3DClient;